package com.jiangjun.fetch.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jiangjun.fetch.mongo.MongoDBSupport;
import com.mongodb.Mongo;

@WebServlet(name = "GetImageServlet", urlPatterns = "/getImageService", asyncSupported = false)
@WebInitParam(name = "default_charset", value = "utf-8")
public class GetImageServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		String src = request.getParameter("src");
		if (null != request.getParameter("w")) {
			String w = request.getParameter("w");
			String[] array = src.split("\\" + File.separator);
			src = src.replace(array[array.length - 1], "") + w
					+ File.separator + array[array.length - 1];
			File f = new File(src);
			if (!f.exists()) {
				src = src.replace(array[array.length - 1], "") + "320"
						+ File.separator + array[array.length - 1];
			}
		} 
		File file = new File(src);
		if (!file.exists()) {
			response.setStatus(500);
		} else {
			InputStream is = new FileInputStream(file);
			int b;
			byte[] buffer = new byte[1024];
			ServletOutputStream sos = null;
			try {
				response.setHeader("Content-Length",
						Integer.toString(is.available()));
				String[] image_type = src.split("\\.");
				response.setHeader("Content-Type", "image/" + image_type[1]);
				response.setHeader("Accept-Ranges", "bytes");
				response.setHeader("Connection", "keep-alive");
				sos = response.getOutputStream();
				while ((b = is.read(buffer)) != -1) {
					sos.write(buffer, 0, b);
					sos.flush();
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				response.setStatus(500);
			} finally {
				if (null != is)
					is.close();
				if (null != sos)
					sos.close();
			}
		}
	}
}
